package org.xmx0632.connector.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmx0632.connector.model.Gateway;

public class GlobalGateway {
	public static final Logger LOG = LoggerFactory.getLogger(GlobalGateway.class);

	// gatewayId:Gateway(channel)
	private static Map<String, Gateway> gatewayId2GatewayMap = new ConcurrentHashMap<String, Gateway>(20000);

	private static Map<String, Gateway> tmpRemoteAddress2GatewayMap = new ConcurrentHashMap<String, Gateway>(20000);

	// TODO 设备发送注册消息上来的时候,绑定gatewayId和channel的关系
	public static boolean register(String remoteAddress, String gatewayId) {
		try {
			Gateway gateway = tmpRemoteAddress2GatewayMap.get(remoteAddress);
			if (gateway == null) {
				return false;
			}
			gateway.setGatewayId(gatewayId);
			// 绑定关系
			gatewayId2GatewayMap.put(gatewayId, gateway);
			return true;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return false;
	}

	public static boolean disconnect(String gatewayId) {
		Gateway obj = gatewayId2GatewayMap.remove(gatewayId);
		return obj != null;
	}

	public static Gateway get(String gatewayId) {
		return gatewayId2GatewayMap.get(gatewayId);
	}

	/**
	 * 客户端第一次连接上来
	 * 
	 * @param remoteAddress
	 * @param gateway
	 */
	public static void connect(String remoteAddress, Gateway gateway) {
		tmpRemoteAddress2GatewayMap.put(remoteAddress, gateway);
	}

	public static void disconnectByRemoteAddress(String remoteAddress) {
		LOG.debug("disconnectByRemoteAddress:{}", remoteAddress);
		Gateway gateway = tmpRemoteAddress2GatewayMap.get(remoteAddress);
		if (gateway != null && gateway.getGatewayId() != null) {
			gatewayId2GatewayMap.remove(gateway.getGatewayId());
		}
		tmpRemoteAddress2GatewayMap.remove(remoteAddress);
	}
}
